package com.spirng.leetcode.day02;

public class LinkedList3 {
    public static void main(String[] args) {
        LinkedList3 myLinkedList = new LinkedList3();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
        int i = myLinkedList.get(1);// 返回 2
        myLinkedList.deleteAtIndex(1);    // 现在，链表变为 1->3
        int i1 = myLinkedList.get(1);
    }
   int size;
   LinkNode head;
    //初始化链表
    public LinkedList3() {
        size = 0;
        head = new LinkNode(0);
    }
    //index重0开始
    public int get(int index){
        if(index<0||index>=size){
            return -1;
        }
        LinkNode linkNode=head;
        for (int i = 0; i <= index; i++) {
            linkNode=linkNode.next;
        }
        return linkNode.val;
    }
    public void addAtTail(int val) {
        LinkNode linkNode = new LinkNode(val);
        LinkNode star=head;
        for (int i=0;i<size;i++){
            star=star.next;
        }
        star.next=linkNode;
        size++;
    }
    public void addAtIndex(int index, int val) {
        if(index>size){
            return;
        }
        if(index<0){
            index=0;
        }
        size++;
        LinkNode pred=head;
        for (int i=0;i<index;i++) {
            pred = pred.next;
        }
        LinkNode linkNode = new LinkNode(val);
        linkNode.next=pred.next;
        pred.next=linkNode;
    }
    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        size--;
        if (index == 0) {
            head = head.next;
            return;
        }
        LinkNode pred = head;
        for (int i = 0; i < index ; i++) {
            pred = pred.next;
        }
        pred.next = pred.next.next;

    }

    public void addAtHead(int val){
        LinkNode linkNode = new LinkNode(val);
        linkNode.next=head.next;
        head.next=linkNode;
        size++;
    }

}
class LinkNode{
    int val;
    LinkNode next;
    LinkNode(){}
    LinkNode(int val){
        this.val=val;
    }
}
